package com.atguigu.lease.web.admin.service.impl;

import com.atguigu.lease.common.config.MinioProperties;
import com.atguigu.lease.common.exception.BusinessException;
import com.atguigu.lease.common.util.UUIDUtils;
import com.atguigu.lease.web.admin.service.FileService;
import io.minio.*;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author liangtiaanzhe
 */
@Service
public class FileServiceImpl implements FileService {

    @Resource
    private MinioProperties minioProperties;
    
    @Resource
    private MinioClient minioClient;

    @Override
    public String upload(MultipartFile file){
        try {
            //判断bucket是否存在
            boolean bucketExists =
                    minioClient.bucketExists(BucketExistsArgs.builder()
                            .bucket(minioProperties.getBucketName())
                            .build());
            //bucket不存在，创建
            if (!bucketExists) {
                //创建bucket
                minioClient.makeBucket(MakeBucketArgs.builder()
                        .bucket(minioProperties.getBucketName()).build());
                //设置bucket策略：私有、公共、自定义
                minioClient.setBucketPolicy(SetBucketPolicyArgs.builder()
                        .bucket(minioProperties.getBucketName())
                        .config(createBucketPolicyConfig(minioProperties.getBucketName())).build());
            }
            String filename = new SimpleDateFormat("yyyyMMdd").format(new Date())+"/"+
                    UUIDUtils.generateUUID() +"-"+file.getOriginalFilename();
            // UUID-01.jpg
            //上传文件到minio
            minioClient.putObject(PutObjectArgs.builder().
                    //bucket名称
                            bucket(minioProperties.getBucketName()).
                    //在bucket文件名称
                            object(filename).
                    stream(file.getInputStream(), file.getSize(), -1).
                    contentType(file.getContentType()).build());

            //返回文件在minio里面地址
            return String.join("/", minioProperties.getEndpoint(),
                    minioProperties.getBucketName(), filename);
        }catch (Exception e){
            throw new BusinessException(e);
        }
    }

    private String createBucketPolicyConfig(String bucketName) {
        return """
            {
              "Statement" : [ {
                "Action" : "s3:GetObject",
                "Effect" : "Allow",
                "Principal" : "*",
                "Resource" : "arn:aws:s3:::%s/*"
              } ],
              "Version" : "2012-10-17"
            }
            """.formatted(bucketName);
    }

}
